package storage

import (
	"navidog/backend/types"
	"sync"

	"gopkg.in/yaml.v3"
)

// 加载或保存配置

type ConnectionStorage struct {
	storage *localStorage
	mutex   sync.Mutex
}

func NewConnectionStorage() *ConnectionStorage {
	storage := NewLocalStorage("navidog.yaml")
	return &ConnectionStorage{storage: storage}
}

func (cs *ConnectionStorage) Save(data *types.ConfigMap) error {
	cs.mutex.Lock()
	defer cs.mutex.Unlock()
	yamlData, err := yaml.Marshal(data)
	if err != nil {
		return err
	}
	return cs.storage.Save(yamlData)
}

func (cs *ConnectionStorage) Load() (*types.ConfigMap, error) {
	cs.mutex.Lock()
	defer cs.mutex.Unlock()
	yamlData, err := cs.storage.Load()
	if err != nil {
		return nil, err
	}
	var configMap types.ConfigMap
	err = yaml.Unmarshal(yamlData, &configMap)
	return &configMap, err
}
